package cn.wolfcode.dao.impl;

import cn.wolfcode.dao.IStudentDAO;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;

@Repository
public class StudentDAOImpl implements IStudentDAO {
    @Autowired
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void save(String username, String password) throws Exception {
        @Cleanup
        Connection connection = dataSource.getConnection();
        @Cleanup
        PreparedStatement ps =
                connection.prepareStatement("insert into student(username,password) " +
                        "values(?,?)");
        ps.setString(1, username);
        ps.setString(2, password);
        ps.executeUpdate();
    }

    @Override
    public void delete(Long id) throws Exception {
        @Cleanup
        Connection connection = dataSource.getConnection();
        @Cleanup
        PreparedStatement ps =
                connection.prepareStatement("delete from student where id = ?");
        ps.setLong(1,id);
        ps.executeUpdate();
    }

    @Override
    public void update(Long id, String username, String password) throws Exception {
        @Cleanup
        Connection connection = dataSource.getConnection();
        @Cleanup
        PreparedStatement ps =
                connection.prepareStatement("update student set username=?,password=?" + "where id = ?");
        ps.setString(1, username);
        ps.setString(2, password);
        ps.setLong(3,id);
        ps.executeUpdate();
    }

    @Override
    public void selectOne(Long id) throws Exception {
        @Cleanup
        Connection connection = dataSource.getConnection();
        @Cleanup
        PreparedStatement ps =
                connection.prepareStatement("select * from student where id = ?");
        ps.setLong(1,id);
        ps.executeQuery();
    }

    @Override
    public void selectAll() {
        try {


            @Cleanup
            Connection connection = dataSource.getConnection();
            @Cleanup
            PreparedStatement ps =
                    connection.prepareStatement("select * from student");
            ps.executeQuery();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
